// pages/short-video-play/index.js
const { globalData } = getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    curQueue: [],
    videoActive: -1, // 视频当前激活索引
    showMask: false, // 显示遮罩，当滑动动画没结束时显示 
    productActive: 0,
  },
  backHandle() {
    wx.navigateBack();
  },
  swiperChangeHandle(event) {
    const {
      current,
      source
    } = event.detail
    if (source == 'touch') {
      this.playCurrent(current);
      this.setData( {
        showMask: true
      });
    }
  },
  animationSwiperChange(event) {
    this.videoSwitch(event.detail.current)
  },

  // 短视频切换
  videoSwitch(current) {
    const {videoActive, curQueue} = this.data;
    let oldId = curQueue[current].id, 
      diff = current - videoActive,
      direction = diff > 0 ? 'up' : 'down';
    this.setData({
      showMask: false,
      videoActive: current
    }, () => {
      if (direction == 'up' && videoActive == curQueue.length - 1) {
        return;
      }
      if (direction == 'down' && videoActive == 0) {
        return;
      }
      let video = direction == 'up' ? curQueue[curQueue.length - 1] : curQueue[0];
      this.requestData(video.sort_num, false).then(res => {
        if (res.success) {
          const {
            next,
            last
          } = res.result;
          if (direction == 'up' && next) {
            if (videoActive == 1) {
              curQueue.shift();
            }
            curQueue.push(this.formatVideo(next, globalData.imageUrl));
          }
          if (direction == 'down' && last) {
            curQueue.unshift(this.formatVideo(last, globalData.imageUrl));
            if (videoActive == 1) {
              curQueue.splice(curQueue.length - 1, 1);
            }
          }
          let index = curQueue.findIndex(item => item.id == oldId);
          this.setData({
            curQueue,
            videoActive: index
          })
        }
      });
    });

    this.setData({
      curQueue,
      showMask: false,
      videoActive: current
    })
  },

  metadataHandle(event) {
    let id = event.currentTarget.dataset.id,
      index = this.data.curQueue.findIndex(item => item.id == id);
    const {
      duration,
    } = event.detail
    if (index > -1) {
      this.setData({
        [`curQueue[${index}].duration`]: duration,
      })
    }
  },
  videoTabHandle(event) {
    let id = event.currentTarget.dataset.id,
      index = this.data.curQueue.findIndex(item => item.id == id);
    if(index > -1) {
      if (this.preContext) {
        let video = this.data.curQueue[index];
        if (video.playStatus == 1) {
          this.preContext.play();
        }
        if(video.playStatus == 2) {
          this.preContext.pause();
        }
      }

      this.setData({
        [`curQueue[${index}].controlsStatus`]: true
      })
    }
  },
  playStartHandle(event) {
    let id = event.currentTarget.dataset.id,
      index = this.data.curQueue.findIndex(item => item.id == id);
    if (index > -1) {
      this.setData({
        [`curQueue[${index}].playStatus`]: 2
      })
    }
  },
  playPauseHandle(event) {
    let id = event.currentTarget.dataset.id,
      index = this.data.curQueue.findIndex(item => item.id == id);
    if (index > -1) {
      this.setData({
        [`curQueue[${index}].playStatus`]: 1,
        [`curQueue[${index}].controlsStatus`]: true
      });
    }
  },
  playEndHandle(event) {
    let {id} = event.currentTarget.dataset;
    let index = this.data.curQueue.findIndex(item => item.id == id);
    if (index > -1) {
      this.setData({
        [`curQueue[${index}].currentTime`]: 0,
      });
    }
  },
  timeUpdateHandle(event) {
    const {currentTime, duration} = event.detail
    let {id} = event.currentTarget.dataset, 
      index = this.data.curQueue.findIndex(item => item.id == id);

    if (index > -1) {
      this.setData({
        [`curQueue[${index}].currentTime`]: currentTime,
        [`curQueue[${index}].duration`]: duration
      })
    }
  },
  playHandle() {
    if(this.preContext) {
      this.preContext.play();
    }
  },
  catchTouchMove() {
    return false;
  },
  playCurrent(current) {
    if (current < 0) {
      return
    }

    if (this.preContext) {
      this.preContext.pause()
    }
    const {
      curQueue,
    } = this.data
    const {
      id
    } = curQueue[current]
    let curContext = wx.createVideoContext(`video_${id}`, this)
    if (curContext) {
      curContext.play();
      this.preContext = curContext
    }
  },
  controlsToggleHandle(event) {
    let id = event.currentTarget.dataset.id,
      index = this.data.curQueue.findIndex(item => item.id == id);
    if (index >= 0) {
      this.setData({
        [`curQueue[${index}].controlsStatus`]: event.detail.show
      })
    }
  },
  // 控制条显示
  positionMoveHandle(event) {
    const time = event.detail
    if (this.preContext) {
      this.preContext.seek(time)
    }
  },
  formatVideo(video, imagePrefix = '') {
    return {
      id: video.id,
      title: video.title,
      sort_num: video.sort_num,
      video_url: imagePrefix + video.video_url,
      playStatus: 1,
      currentTime: 0,
      duration: 0,
      controlsStatus: false
    }
  },
  requestData(current_sort_num, loading = true) {
    return wx.ajax.post('querNextInfo.action', {
      current_sort_num,
      type: this.type
    }, loading);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let {
      video
    } = options;

    video = JSON.parse(decodeURIComponent(video))
    this.type = video.type;
    video = this.formatVideo(video);
    video.playStatus = 2;
    this.requestData(video.sort_num).then(res => {
      if (res.success) {
        const {
          next,
          last
        } = res.result;
        let curQueue = [video];
        if (next) {
          curQueue.push(this.formatVideo(next, globalData.imageUrl));
        }
        if (last) {
          curQueue.unshift(this.formatVideo(last, globalData.imageUrl));
        }
        let index = curQueue.indexOf(video);
        this.setData({
          curQueue,
          videoActive: index
        }, () => {
          this.playCurrent(index);
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      path: `/pages/short-video-play/index?video=${JSON.stringify(this.data.curQueue[this.data.videoActive])}`
    }
  }
})